package com.ktg.common.utils.poi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.logging.Logger;

/**
 * Created by huangzheng on 2016/11/29.
 */
public class ExcelClass {

    public   int row;
    public  String name;

    private static Logger log = Logger.getLogger(String.valueOf(ExcelClass.class));

    private final static String excel2003L = ".xls"; // 2003- 版本的excel
    private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel

    public ExcelClass(int row,String name){
        this.row=row;
        this.name=name;
    }

    /**
     * 将流中的Excel数据转成List<Map>
     *
     * @param in
     *            输入流
     * @param fileName
     *            文件名（判断Excel版本）
     * @param mapping
     *            字段名称映射
     * @return
     * @throws Exception
     */
    public static List<Object> parseExcel(InputStream in, String fileName,
                                          List<ExcelClass> mapping) throws Exception {
        return parseExcel(in,fileName,mapping, 1);
    }

    /**
     * 将流中的Excel数据转成List<Map>
     *
     * @param in
     *            输入流
     * @param fileName
     *            文件名（判断Excel版本）
     * @param mapping
     *            字段名称映射
     * @return
     * @throws Exception
     */
    public static List<Object> parseExcel(InputStream in, String fileName,
                                                       List<ExcelClass> mapping,int dataNum) throws Exception {
        // 根据文件名来创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        // 返回数据
        List<Object> ls =new  JSONArray();

        // 遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null)   continue;
                //获得总列数
            int coloumnum = sheet.getRow(0).getPhysicalNumberOfCells();
            int rownum = sheet.getLastRowNum();//获得总行数
            for (int c = dataNum; c < rownum; c++) {
                if (sheet.getRow(c) == null)continue;
                Map<String, Object> m = new HashMap<String, Object>();
                for (int j = 0; j < mapping.size(); j++) {
                    ExcelClass s = mapping.get(j);
                    cell = sheet.getRow(c).getCell(s.row);
                    String value =  new DataFormatter().formatCellValue(cell);
                    if (cell == null || value.isEmpty()) continue;
                    m.put(s.name,value );
                }
                if (m.isEmpty())continue;
                System.out.println("m"+JSON.toJSONString(m.isEmpty()));
                ls.add(m);
            }

        }
        work.close();
        return ls;
    }


    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     *
     * @param inStr
     *            ,fileName
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inStr); // 2003-
        } else if (excel2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inStr); // 2007+
        } else {
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }

    public static void main(String[] args) throws Exception {
        File file = new File("C:\\Users\\86135\\Desktop\\产品检测记录(2022.01).xls");
        FileInputStream fis = new FileInputStream(file);


        List<ExcelClass> ls = new ArrayList<ExcelClass>();
        ls.add(new ExcelClass(0,"产品名称1"));
        ls.add(new ExcelClass(1,"型号"));
        ls.add(new ExcelClass(2,"粘度"));
        System.out.println("ls"+JSON.toJSONString(ls));
        List<Object> lls = parseExcel(fis, file.getName(), ls);
        System.out.println(JSON.toJSONString(lls));
    }

}
